package com.biboheart.adapter.compiler;

import com.biboheart.adapter.compiler.ast.Node;
import com.biboheart.adapter.support.utils.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class CompilerBuilder {
    private static volatile Compiler sharedInstance;

    public static Compiler getSharedInstance() {
        Compiler compiler = sharedInstance;
        if (null == compiler) {
            synchronized (CompilerBuilder.class) {
                compiler = sharedInstance;
                if (compiler == null) {
                    compiler = new NormalCompiler();
                    sharedInstance = compiler;
                }
            }
        }
        return compiler;
    }

    public static Node ast(String expr) {
        return CompilerBuilder.getSharedInstance().build(expr);
    }

    // 将{"name":"expr"}格式的内容转换成ast对象
    @SuppressWarnings("unchecked")
    public static Map<String, Node> build(String content) throws JsonProcessingException {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        Map<String, Node> nodeMap = new HashMap<>();
        Map<String, String> map = JsonUtils.json2objWithType(content, Map.class);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            nodeMap.put(entry.getKey(), CompilerBuilder.getSharedInstance().build(entry.getValue()));
        }
        return nodeMap;
    }
}
